<template>
  <je-modal
    v-model:visible="visibleModule"
    width="600px"
    :title="$t('viewModal.changePkValue')"
    class="modal-updatekey"
    height="auto"
    :resize="false"
    :maximizable="false"
    :ok-button="addModule"
    cancel-button
    @close="cancelModal"
  >
    <je-form model="modelRef">
      <je-form-item v-bind="validateInfos.pkCode" name="pkCode">
        <je-radio-group v-model:value="modelRef.pkCode" :options="pkValueOptions" :cols="1" />
      </je-form-item>
    </je-form>
  </je-modal>
</template>
<script>
  import { defineComponent, ref, watch, reactive } from 'vue';
  import { Modal, Radio, Form } from '@jecloud/ui';
  import { verifyData } from '../../../helper/common';

  const useForm = Form.useForm;
  export default defineComponent({
    name: 'UpdateViewKey',
    components: {
      JeModal: Modal,
      JeForm: Form,
      JeFormItem: Form.Item,
      JeRadioGroup: Radio.Group,
    },
    props: {
      modalShow: {
        type: Boolean,
        default: false,
      },
      modalData: {
        type: Array,
        default: () => {
          return [];
        },
      },
      checkedCode: {
        type: String,
        default: '',
      },
    },
    emits: ['changePkValue'],
    setup(props, { emit }) {
      //保存模块数据，关闭弹窗
      const visibleModule = ref(props.modalShow);
      const pkValueOptions = ref(props.modalData);
      const modelRef = reactive({
        pkCode: props.checkedCode,
      });
      watch(
        () => props.modalData,
        (newVal) => {
          pkValueOptions.value = newVal;
        },
      );

      const cancelModal = () => {
        emit('changePkValue', 'cancel');
      };
      const rulesRef = reactive({
        pkCode: [verifyData.required],
      });
      const { resetFields, validate, validateInfos } = useForm(modelRef, rulesRef, {
        onValidate: (...args) => {},
      });
      const addModule = ({ $modal, button }) => {
        const modal = $modal,
          btn = button;
        btn.loading = true;
        validate()
          .then(() => {
            btn.loading = false;
            modal.close();
            emit('changePkValue', modelRef.pkCode);
          })
          .catch((error) => {
            btn.loading = false;
          });
        return false;
      };
      return {
        validateInfos,
        resetFields,
        modelRef,
        cancelModal,
        visibleModule,
        addModule,
        pkValueOptions,
      };
    },
  });
</script>
<style lang="less" scoped></style>
